﻿using JustSiteWorker.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace JustSiteWorker.Controllers
{
    public class HomeController : BaseController
    {
        //
        // GET: /Home/


        #region Login
        public ActionResult Login(string id)
        {
            if (string.IsNullOrEmpty(id))
                return View();

            User user = repos.GetUser(id);
            ViewBag.Name = user == null ? "" : user.Name;

            return View(new UserViewModel() { Name = user.Name });
        }

        [HttpPost]
        public ActionResult Login(UserViewModel user)
        {
            User u = repos.GetUser(user.Name, LoginHelper.EncodePassword(user.Password, user.Name));
            //find user 
            if (u == null)
            {
                ModelState.AddModelError(string.Empty, "Не правильный код :(");
                return View(user);
            }

            //if user exist create session
            Session["Id"] = u.Id;
            Session["Name"] = u.Name;
            Session["Email"] = u.Email;
            Session["Role"] = u.Role;
            Session["Icon"] = u.Avatar;

            if (u.Role == (int)Role.Admin)
                return RedirectToAction("Admin", "Home");
            else
            {
                GetClientInfo();
                return RedirectToAction("Index", "Home");
            }
        }
        #endregion

        #region Admin Page
        public ActionResult Admin()
        {
            return View(repos.Users);
        }

        public ActionResult AddUser()
        {
            return View(new UserViewModel());
        }

        [HttpPost]
        public ActionResult AddUser(UserViewModel user)
        {
            if (string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Email) || string.IsNullOrEmpty(user.Avatar) || string.IsNullOrEmpty(user.Password))
            {
                user.ValidateError = true;
                return View(user);
            }

            repos.CreateUser(user.ConvertToUser());

            return RedirectToAction("Admin");
        }
        #endregion

        #region Statistika
        public ActionResult Statistika(int id)
        {
            //get user statistika
            List<Statistika> list = repos.GetStatistika(id);
            return View(list);
        }
        #endregion

        public ActionResult Index()
        {
            ViewBag.IsPrelude = repos.GetUser(UserId).LastVisit == null ? true.ToString() : false.ToString();

            return View(repos.Comments);
        }

        [HttpPost]
        public ActionResult AddComment(string message)
        {
            Comment last = repos.GetLastComment();

            int side;
            int margin = (int)Margin.Smal;
            //find
            if (last == null)
                side = (int)Side.Left;
            else
                if (last.UserId == UserId)
                    side = last.Side;
                else
                {
                    side = last.Side == (int)Side.Left ? (int)Side.Right : (int)Side.Left;
                    margin = (int)Margin.Big;
                }

            Comment com = new Comment()
            {
                Message = message,
                Date = DateTime.Now.AddHours(2),
                UserId = UserId,
                Side = side,
                Margin = margin
            };
            repos.AddComment(com);

            User user = repos.GetUser(4);

            return Json(new
            {
                Id = com.Id,
                Message = com.Message,
                Date = com.Date.ToString("dd.mm.yyyy hh:mm"),
                UserName = Session["Name"],
                Icon = Session["Icon"],
                Side = com.Side,
                Margin = com.Margin
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult GetNewMessage(List<int> list)
        {
            List<int> comments = repos.Comments.Select(i => i.Id).ToList();
            if (comments == null || comments.Count == 0)
                return Json(new { Update = false }, JsonRequestBehavior.AllowGet);

            List<int> result = comments.Except(list).ToList();

            List<object> o = new List<object>();
            Comment com;
            foreach (int id in result)
            {
                com = repos.GetComment(id);
                if (com.UserId != UserId)
                {
                    o.Add(new
                    {
                        Id = com.Id,
                        Message = com.Message,
                        Date = com.Date.ToString("dd.mm.yyyy hh:mm"),
                        UserName = com.User.Name,
                        Icon = com.User.Avatar,
                        Side = com.Side,
                        Margin = com.Margin
                    }
                        );
                }
            }

            return Json(new
            {
                Update = o.Count == 0 ? false : true,
                Data = o
            }, JsonRequestBehavior.AllowGet);

            /*List<int> comments = repos.Comments.Select(i => i.Id).ToList();
            List<int> result = comments.Except(list).ToList();

            foreach (int id in result)
            {
                if (id != (int)Session["Id"])
                    result.Remove(id);
            }

            List<object> o = new List<object>();
            Comment com;
            foreach (int id in result)
            {
                com = repos.GetComment(id);

                o.Add(new
                {
                    Id = com.Id,
                    Message = com.Message,
                    Date = com.Date.ToString("dd.mm.yyyy hh:mm"),
                    UserName = com.User.Name,
                    Icon = com.User.Avatar,
                    Side = com.Side,
                    Margin = com.Margin
                }
                    );
            }

            return Json(new
            {
                Update = o.Count == 0 ? false : true,
                Data = o
            }, JsonRequestBehavior.AllowGet);
            return Json(new
            {
                Update = false
            }, JsonRequestBehavior.AllowGet);*/
        }

        private void GetClientInfo()
        {
            string error = string.Empty;

            try
            {
                Statistika statistik = new Statistika();

                //get Host
                statistik.Host = System.Web.HttpContext.Current.Request.UserHostAddress;

                var hostInfo = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]);
                if (hostInfo.AddressList.Count() > 2)
                {
                    //get IP
                    statistik.Ip = hostInfo.AddressList[2].ToString();

                    //get assress family
                    statistik.Family = hostInfo.AddressList[2].AddressFamily.ToString();
                }
                else
                {
                    statistik.Ip = getIPAddress(Request);
                    statistik.Family = string.Empty;
                }
                //get machine name
                statistik.PCName = hostInfo.HostName.Split(new Char[] { '.' })[0].ToString();

                //tests
                //string[] userLanguages = Request.UserLanguages;
                statistik.Browser = Request.Browser.Browser;
                statistik.Br_Platform = Request.Browser.Platform;
                statistik.Br_Version = Request.Browser.Version;

                statistik.Time = DateTime.Now.AddHours(2);
                statistik.UserId = UserId;

                repos.AddStatistika(statistik);
            }
            catch { }
        }

        public static string getIPAddress(HttpRequestBase request)
        {
            string szRemoteAddr = request.UserHostAddress;
            string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
            string szIP = "";

            if (szXForwardedFor == null)
            {
                szIP = szRemoteAddr;
            }
            else
            {
                szIP = szXForwardedFor;

            }
            return szIP;
        }

        [HttpPost]
        public ActionResult GenaretCod(int length)
        {
            string cod = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
            cod = cod.Substring(0, length);

            return Json(cod, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public void CheckSession()
        {
            try
            {
                if (Session == null || (int)Session["Role"] == (int)Role.Admin || UserId == null) return;

                repos.UpdateSession(UserId);
            }
            catch { }
        }

        [HttpPost]
        public void ClearActivity(int id)
        {
            User user = repos.GetUser(id);
            user.LastVisit = null;
            repos.EditUser(user);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            Session.Clear();

            return RedirectToAction("Login", "Home");
        }
    }
}
